package org.meruvian.yama.security.token;

import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.meruvian.yama.entity.User;
import org.meruvian.yama.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


/**
 * 
 * @author vick
 * 
 */
public class ServiceInterceptor extends HandlerInterceptorAdapter {

	private static final long serialVersionUID = 1531336415318477425L;

	private Map<String, Object> model = new HashMap<String, Object>();
	
	@Autowired
	private UserService service;

	public boolean preHandle(HttpServletRequest request, 
			HttpServletResponse response, Object handler)
	    throws Exception {
		// Handle for web browser client
//		if (handler == null) {
//			return false;
//		}
//
//		if (handler.getContentType().equalsIgnoreCase("application/xhtml+xml")) {
//			return false;
//		}

		if (request.getServletPath().startsWith("/user")) {
			return true;
		}

//		OutputStreamWriter streamWriter = new OutputStreamWriter(
//				response.getOutputStream());

		model = new HashMap<String, Object>();
		model.put("encoding", response.getCharacterEncoding());
		model.put("content-type", response.getContentType());
		model.put("status", "error");

		if (request.getParameter("key") != null) {
			User user = service.getBySecret(request.getParameter("key"));

			if (user != null) {
				return true;
			}
		}
//		handler.fromObject(model, invocation.getResultCode(), streamWriter);
//		streamWriter.flush();

		return true;
 
	}
	

	public Map<String, Object> getModel() {
		return model;
	}
}
